const app = getApp();
const WxParse = require('../wxParse/wxParse')
import {
  getPostsbyID,
  getCategoryByID,
  getRandPosts,
  getPostsList,
  getCategories,
  getRelatePost,
  getUserPosts,
  getLiveLists,
  getReplays


} from "../api/article";
import {
  fav,
  like,
  updateFollow,
  getProfile
} from "../api/common.js";




/*
 * 获取文章父分类
 */
const getCategoriesList = function (args) {
  getCategories(args).then(res => {
      let args = {}
      if (res.length != 0) {
        args.categoryMap = this.data.categoryMap.concat(res.map(function (item) {
          item.posts = [];
          item.page = 1;
          item.isLastPage = false;
          return item;
        }));
      } else {
        args.categoryMap = [{
          name: '全部分类'
        }];
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      //this.setData({isMessage:true})
    })
}



/**获取文章 */
const getPosts = function (data) {
  let that = this;
  let args={};
  getPostsList(data).then(res => {
      if (res.status == 500) {
        this.setData({
          isLastPage: true,
          loadtext: '该用户暂时未发布任何内容',
        })

      } else {
        if (res.length < 10) {
          this.setData({
            isLastPage: true,
            loadtext: '到底啦',
          })
        }
        if (this.data.isBottom) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
          args.articleload = false
        } else {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
          args.articleload = false
        }
        that.setData(args);
      }
    })
    .catch(err => {
      console.log(err)
    })
}

/**
 * 获取随机文章
 */

const getRandPostsList = function () {
  getRandPosts().then(res => {
      let data = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
        })
      }
      data.randPosts = res;
      this.setData(data)
    })
    .catch(err => {
    })
}
/**
 * 
 * 获取文章详情
 */

const getPostsDetail = function () {
  let id = this.data.id
  getPostsbyID(id).then(res => {
      let args = {}
      let current = getCurrentPages()
      if (current.length === 1) {
        args.isShare = true
      }
      args.showloading = false
      WxParse.wxParse('article', 'html', res.content.rendered, this, 5)
      if (res.media && res.media.audio) {
        backgroundAudioManager.title = res.title.rendered
        backgroundAudioManager.coverImgUrl = res.meta.thumbnail
        // 设置了 src 之后会自动播放
        backgroundAudioManager.src = res.media.audio
        this.setData({
          isPlay: true
        })
      }
      let videoAdLogs = wx.getStorageSync('videoAdLogs') || [];
      if (videoAdLogs.indexOf(this.data.id) > -1) {
        args.we_video_ad = false
      } else {
        args.we_video_ad = res.we_video_ad
      }
      args.isPull = false
      //args.isShow = true
      args.detail = res
      args.isLike = res.islike;
      args.isfav = res.isfav;
      if (res.comments != 0) {
        args.isComments = true
        this.getPostsComments()
      }
      if (res.isvote) {
        let count = 0
        for (let i = 0; i < res.vote.options.length; i++) {
          count += res.vote.options[i].count;
        }
        args.count = count
      }
      args.showSkeleton = false
      //  this.getRelatedPosts()
      // this.getDetailAds()
      this.setData(args)
      // 阅读记录缓存数据
      let record = {}
      let title = {}
      let excerpt = {}
      let categories = []
      let cate = {}
      let meta = {}
      record.id = res.id
      record.type = res.type
      record.date = res.date
      title.rendered = res.title.rendered
      excerpt.rendered = res.excerpt.rendered
      cate.name = res.categories[0].name
      categories[0] = cate
      meta = res.meta
      record.meta = meta
      record.comments = res.comments
      record.favs = res.favs
      record.likes = res.likes
      record.title = title
      record.excerpt = excerpt
      record.categories = categories
      // 调用 API 从本地缓存中获取阅读记录并记录
      let logs = wx.getStorageSync('readLogs') || []
      let readsave = true
      // 过滤重复值
      if (logs.length > 0) {
        for (let i = 0; i < logs.length; i++) {
          if (logs[i].id == res.id) {
            readsave = false
            break;
          }
        }
      }
      if (readsave) {
        logs.unshift(record)
      }
      // 如果超过指定数量
      if (logs.length > 9) {
        logs.pop(); // 去除最后一个
      }
      wx.setStorageSync('readLogs', logs)
      //阅读记录缓存结束
      wx.stopPullDownRefresh()
    })
    .catch(err => {
      if (this.data.isPull) {
        this.setData({
          isPull: false
        })
        wx.stopPullDownRefresh()
      }
    })
}

/**
 * 文章跳转
 */
const goDetail = function (e) {
  let id = e.currentTarget.id;
  let type = e.currentTarget.dataset.type;
  wx.navigateTo({
    url: '/pages/detail/detail?id=' + id + '&type=' + type,
  })
}


/**
 * 获取相关文章
 */

const getRelatePosts = function (id) {
  getRelatePost(id).then(res => {
    let args = [];
    args.relatePost = res;
    this.setData(args)
  })

}

/**
 * 获取发过的帖子
 */

const getUserArticle = function (id, page) {
  let args = {},
    that = this
  getUserPosts(id, page).then(res => {
      if (res.status == 500) {
        this.setData({
          isLastPage: true,
          loadtext: '该用户暂时未发布任何内容',
        })

      } else {
        let args = {}
        args.showloading = false;
        if (res.length == 0) {
          this.setData({
            nodate: true
          })
        }
        if (res.length < 10) {
          this.setData({
            nodata: true,
            showloadmore: false,
            isLastPage: true,
            loadtext: '到底啦'
          })
        }
        if (this.data.isPull) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
        } else if (this.data.isBottom) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
        } else {
          args.nowNote = res[1]
          args.posts = res
          args.page = this.data.page + 1
        }
        if (this.data.isPull) {
          wx.stopPullDownRefresh()
        }
        if (args.posts != []) {
          args.isList = true
        }
        args.loading = true;
        args.showLoading = false;
        args.topicload = false;
        args.isPull = false
        this.setData(args)
      }
    })
    .catch(err => {
  
    })
}


const getLiveList=function(data) {
  getLiveLists(data).then(res => {
      let args = {}
      args.showloading = false;
      if (res.length == 0) {
        this.setData({
          nodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.posts = res
        args.page = this.data.page + 1
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}


const getReplay= function(data) {
  getReplays(data).then(res => {
      let args = {}
      args.showloading = false;
      if (res.length == 0) {
        this.setData({
          nodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.posts = res
        args.page = this.data.page + 1
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}

module.exports = function (obj) {
  obj.getPosts = getPosts;
  obj.getCategoriesList = getCategoriesList;
  obj.getRandPostsList = getRandPostsList;
  obj.getPostsDetail = getPostsDetail;
  obj.goDetail = goDetail;
  obj.getRelatePosts = getRelatePosts;
  obj.getUserArticle = getUserArticle;
  obj.getLiveList=getLiveList;
  obj.getReplay=getReplay;
}